import os
import subprocess
from functools import partial
from loguru import logger

subprocess.Popen = partial(subprocess.Popen, encoding='utf-8')

import requests
from lxml import etree
import execjs

DIR_PATH = os.path.dirname(os.path.abspath(__file__))

# html页面
url = "https://sugh.szu.edu.cn/Html/News/Columns/540/Index.html"
server_cookie_name = 'ihkYnttrQXfVO'
js_cookie_name = 'ihkYnttrQXfVP'
host = "sugh.szu.edu.cn"
headers = {
    "Host": host,
    "Connection": "keep-alive",
    "Cache-Control": "max-age=0",
    "Upgrade-Insecure-Requests": "1",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
    "Accept-Encoding": "gzip, deflate, br",
    "Accept-Language": "zh-CN,zh;q=0.9"
}
cookies = {
}

request_session = requests.session()
request_session.headers.update(headers)
request_session.cookies.update(cookies)


def get_code():
    response = request_session.get(url)
    print(response)  # 412
    cookies[server_cookie_name] = response.cookies[server_cookie_name]
    request_session.cookies.update(cookies)
    html = etree.HTML(response.text)
    meta_content = html.xpath('//meta[2]/@content')[0]
    js_code = html.xpath('//script[@r="m" and position()=2]/text()')[0]

    return meta_content, js_code


meta_content, js_code = get_code()

with open(os.path.join(DIR_PATH, "深圳大学总医院.js"), 'r', encoding='utf-8') as js_file:
    js_text = js_file.read()
    js_text = js_text.replace('meta_content', meta_content)
    js_text = js_text.replace("'js_code'", js_code)

js = execjs.compile(js_text)
result = js.call('main')
f80t = result.split('=', maxsplit=1)[1].split('; path')[0]
logger.success(f"{js_cookie_name}长度：{len(f80t)}  值：【{f80t}】")  # 217
cookies[js_cookie_name] = f80t
request_session.cookies.update(cookies)

# url2 = 'https://www.10010.com/mall/service/query/QueryNavigations'
# url2 = js.call('getUrl', url2)
# logger.success(url2)
# response = request_session.post(url2)

response = request_session.get(url)
response.encoding = 'utf-8'
print(response.text)
logger.info(response)  # tourist
